<template>
    <div>
        <!--面包屑导航-->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>分类参数</el-breadcrumb-item>
        </el-breadcrumb>
        <!--
            卡片视图区域
            警告区域 :closable="false" (是否展示 x 号)  show-icon 展示图标
        -->
        <el-card>
            <el-alert
                    title="注意：只允许为第三级分类设置相关参数"
                    type="warning" :closable="false" show-icon>
            </el-alert>
        <!--选择商品分类区域-->
            <el-row class="cat_opt">
                <el-col>
                    <span>选择商品分类：</span>
                    <!--选择商品分类的级联选择框-->
                    <el-cascader
                            v-model="selectedCateKeys"
                            :options="cateList"
                            :props="cateProps"
                            @change="handleChange"></el-cascader>
                </el-col>
            </el-row>

            <!--tab页签显示区域-->
            <el-tabs v-model="activeName" @tab-click="handleTabClick">
                <!--添加动态参数的面板,将标签页修改成many-->
                <el-tab-pane label="动态参数" name="many">
                    <el-button type="primary" size="mini" :disabled="isButtonDisabled" @click="addParamdialogVisible = true">添加动态参数</el-button>
                    <!--动态参数表格-->
                    <el-table :data="manyTableData" border stripe>
                        <!--展开行-->
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag
                                        v-for="(item,key) in scope.row.attr_vals"
                                        :key="key"
                                        closable
                                        @close="handleClose(key,scope.row)"
                                >
                                    {{item}}
                                </el-tag>
                                <!--输入框-->
                                <el-input
                                        class="input-new-tag"
                                        v-if="scope.row.inputVisible"
                                        v-model="scope.row.inputValue"
                                        ref="saveTagInput"
                                        size="small"
                                        @keyup.enter.native="handleInputConfirm(scope.row)"
                                        @blur="handleInputConfirm(scope.row)"
                                >
                                </el-input>
                                <!--添加按钮-->
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <!--索引列-->
                        <el-table-column type="index" label="#"></el-table-column>
                        <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button size="mini" type="primary" icon="el-icon-edit" @click="editParamdialog(scope.row.attr_id)">编辑</el-button>
                                <el-button size="mini" type="danger" icon="el-icon-delete"  @click="removeParams(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <!--添加静态参数的面板,将标签页修成成only-->
                <el-tab-pane label="静态参数" name="only">
                    <el-button type="primary" size="mini" :disabled="isButtonDisabled" @click="addParamdialogVisible = true">添加静态参数</el-button>
                    <!--静态参数表格-->
                    <el-table :data="onlyTableData" border stripe>
                        <!--展开行-->
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag
                                        v-for="(item,key) in scope.row.attr_vals"
                                        :key="key"
                                        closable
                                        @close="handleClose(key,scope.row)"
                                >
                                    {{item}}
                                </el-tag>
                                <!--输入框-->
                                <el-input
                                        class="input-new-tag"
                                        v-if="scope.row.inputVisible"
                                        v-model="scope.row.inputValue"
                                        ref="saveTagInput"
                                        size="small"
                                        @keyup.enter.native="handleInputConfirm(scope.row)"
                                        @blur="handleInputConfirm(scope.row)"
                                >
                                </el-input>
                                <!--添加按钮-->
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <!--索引列-->
                        <el-table-column type="index"></el-table-column>
                        <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                        <el-table-column>
                            <template slot-scope="scope">
                                <el-button size="mini" type="primary" icon="el-icon-edit" @click="editParamdialog(scope.row.attr_id)">编辑</el-button>
                                <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeParams(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>

        <!--添加参数对话框-->
        <el-dialog
                :title="'添加' + titleTxt"
                :visible.sync="addParamdialogVisible"
                width="30%" @close="closeaddParamdialogVisible">
           <!--添加表单-->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px">
                <el-form-item :label="titleTxt" prop="attr_name">
                    <el-input v-model="addForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
            <el-button @click="addParamdialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addParams">确 定</el-button>
          </span>
        </el-dialog>

        <!--编辑参数对话框-->
        <el-dialog
                :title="'编辑' + titleTxt"
                :visible.sync="editParamdialogVisible"
                width="30%" @close="closeeditParamdialogVisible">
            <!--添加表单-->
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px">
                <el-form-item :label="titleTxt" prop="attr_name">
                    <el-input v-model="editForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
            <el-button @click="editParamdialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editParams">确 定</el-button>
          </span>
        </el-dialog>

    </div>
</template>

<script>
    export default {
        data (){
            return {
                //分类列表
                cateList : [],
                cateProps : {
                    expandTrigger: 'hover',
                    value : 'cat_id',
                    label : 'cat_name',
                    children : 'children'
                },
                //联级选择器选中的值
                selectedCateKeys : [],
                //tab页签激活显示的页签项
                activeName : 'many',
                //动态数据
                manyTableData : [],
                //静态数据
                onlyTableData : [],
                //添加参数对话框的显示和隐藏
                addParamdialogVisible : false,
                //编辑参数对话框的显示和隐藏
                editParamdialogVisible : false,
                //添加表单的model
                addForm : {
                    attr_name : ''
                },
                //编辑表单的model
                editForm : {
                    attr_name : ''
                },
                //添加表单验证规则
                addFormRules : {
                    attr_name : [
                        {required:true,message:'参数名称不能为空', trigger:'blur'}
                    ]
                },
                //编辑表单验证规则
                editFormRules : {
                    attr_name : [
                        {required: true , message: '参数名称不能为空' , trigger: 'blur'}
                    ]
                }
            }
        },
        created() {
            this.getCateList();
        },
        methods:{
            async getCateList(){
                //获取所有商品的分类数据
                const { data : res } = await this.$http.get('categories');
                if(res.meta.status !== 200){
                    return this.$http.error('获取商品分类列表失败');
                }
                //如果获取参数成功后,就进行赋值
                this.cateList = res.data;
            },
            //当联级参数发生变化的时候
            handleChange(){
                this.getPramsByChange();
            },
            //当点击tab标签的时候触发
            handleTabClick(){
                this.getPramsByChange();
            },
            //获取参数
            async getPramsByChange(){
                //当用户在联级菜单中选择内容的时候发生变化
                //我们这边只能给三级分类设置参数
                if(this.selectedCateKeys.length !== 3){
                    //当没有选中三级参数的时候,将选中的key进行清空
                    this.selectedCateKeys = [];
                    //将table表格中的数据也进行清空
                    this.manyTableData = [];
                    this.onlyTableData = [];
                    return false;
                }
                //当tab的值发生变化的时候,获取对应的参数
                //发送请求,根据用户选择的三级分类和面板获取参数数据
                const { data : res } = await this.$http.get(`categories/${this.cateId}/attributes`,{params:{sel:this.activeName}});
                if(res.meta.status !== 200){
                    return this.$message.error('获取参数失败');
                }
                //将attr_valus的值转化为数组用作标签显示
                res.data.forEach(elem => {
                    elem.attr_vals = !!elem.attr_vals ? elem.attr_vals.split(',') : [];
                    //添加一个布尔值控制文本框的显示或者隐藏
                    elem.inputVisible = false;
                    //添加一个inputValue保存文本框值
                    elem.inputValue = '';
                })
                //将获取到的数据进行保存，这里的保存要根据不同的情况分别进行保存
                if(this.activeName === 'many'){
                    this.manyTableData = res.data;
                }else{
                    this.onlyTableData = res.data;
                }

            },
            //关闭添加参数对话框
            closeaddParamdialogVisible(){
                this.$refs.addFormRef.resetFields();
            },
            closeeditParamdialogVisible(){
                this.$refs.editFormRef.resetFields();
            },
            //添加参数操作
            addParams(){
                this.$refs.addFormRef.validate(async valid => {
                    if(!valid){
                        return this.$message.error('请填写完整的信息');
                    }
                    const {data : res} = await this.$http.post(`categories/${this.cateId}/attributes`,{
                        attr_name : this.addForm.attr_name,attr_sel:this.activeName
                    });
                    if(res.meta.status !== 201){
                        return this.$message.error(res.meta.msg);
                    }
                    //添加成功了
                    this.$message.success(this.titleTxt + res.meta.msg);
                    //关闭对话框
                    this.addParamdialogVisible = false;
                    //刷新数据
                    this.getPramsByChange();
                });
            },
            //编辑参数操作
            editParams(){
                this.$refs.editFormRef.validate(async valid => {
                    if(!valid){
                        return this.$message.error('请输入完整的参数内容!');
                    }
                    //验证通过进行请求数据的操作
                    const {data : res} = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`,{
                        attr_name : this.editForm.attr_name,attr_sel : this.activeName
                    });
                    if(res.meta.status !== 200){
                        return this.$message.error('参数修改失败');
                    }
                    //如果修改成功
                    this.$message.success(res.meta.msg);
                    //关闭修改的弹窗
                    this.editParamdialogVisible = false;
                    //重新刷新分类数据
                    this.getPramsByChange();

                });
            },
            //编辑参数页面
            async editParamdialog(attrId){
                //根据接口查询当前参数的数据
                const {data : res} = await this.$http.get(`categories/${this.cateId}/attributes/${attrId}`,{
                    params:{attr_sel : this.activeName}
                });
                if(res.meta.status !== 200){
                    return this.$message.error('参数信息获取失败');
                }
                this.editForm = res.data;
                this.editParamdialogVisible = true;
            },
            //删除参数
            async removeParams(scope){
                 const confirmResult =  await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err => err);
                 if(confirmResult === 'cancel'){
                     return this.$message.warning('已取消了删除');
                 }
                 //如果真的进行了删除，就进行删除操作
                const {data : res} = await this.$http.delete(`categories/${scope.cat_id}/attributes/${scope.attr_id}`);
                 if(res.meta.status !== 200){
                    return this.$message.error('删除失败');
                 }
                 //删除成功
                this.$message.success('删除成功');
                this.getPramsByChange();
            },
            async handleInputConfirm(row) {
                //如果当前的值是空的，是无效的,就进行表单重置
                if(row.inputValue.trim().length === 0){
                    row.inputValue = '';
                    row.inputVisible = false;
                    return false;
                }
                //如果是有值的,就可以继续进行后续操作了
                //如果用户输入的数据是合法的,就需要进行保存了
                row.attr_vals.push(row.inputValue.trim());
                this.saveAttrVals(row);
                //当push进去之后就会多一条数据
                row.inputValue = '';
                row.inputVisible = false;

            },
            //点击显示输入框
            showInput(row) {
                //用户点击添加按钮的时候触发
                row.inputVisible = true;
                //$nextTick:在页面上的元素被重新渲染之后，调用回调函数的代码
                this.$nextTick(_ => {
                    //让文本框自动获得焦点
                    this.$refs.saveTagInput.$refs.input.focus();
                });
            },
            handleClose(key,row){
                //对参数属性进行删除操作,从key这个索引开始删除一条数据
                row.attr_vals.splice(key,1);
                this.saveAttrVals(row);
            },
            async saveAttrVals(row){
                //进行数据请求
                const {data : res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
                    attr_name : row.attr_name,attr_sel:row.attr_sel,attr_vals:row.attr_vals.join(',')
                });
                if(res.meta.status !== 200){
                    return this.$message.error('操作失败');
                }
                this.$message.success('操作成功');
            }
        },
        //计算属性
        computed:{
            //添加计算属性用来获取按钮的禁用或者启用
            //使用计算属性来对属性进行设置
            isButtonDisabled(){
                return this.selectedCateKeys.length !== 3;
            },
            //获取选中的三级分类的Id
            cateId(){
                //如果确实选择了三级分类
                if(this.selectedCateKeys.length === 3){
                    return this.selectedCateKeys[this.selectedCateKeys.length - 1];
                }
                //如果没有选择三级分类
                return null;
            },
            //当前添加的属性类型---当两种情况使用一个组件的时候，使用计算属性来改变值并且进行显示
            titleTxt(){
                return this.activeName === 'many' ? '动态参数' : '静态参数';
            }
        }
    }
</script>

<style scoped>
    .el-card{
        margin-top: 7px;
    }
    .cat_opt{
        margin-top: 30px;
        margin-bottom: 30px;
    }
    .el-table{
        margin-top: 7px;
    }
    .el-tag{
        margin-left: 10px;
        margin-top: 5px;
    }
    .input-new-tag{
        width: 120px;
        margin-left: 10px;
    }
    .button-new-tag{
        margin-left: 10px;
    }
</style>
